package com.mxx.bu_yang.activity.on_line;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mxx.basic.server.RetrofitHelper;
import com.mxx.basic.server.enums.RequestEnum;
import com.mxx.basic.utils.MapUrlParamsUtils;
import com.mxx.basic.utils.SPUtils;
import com.mxx.basic.utils.ToastUtils;
import com.mxx.bu_yang.R;
import com.mxx.bu_yang.activity.LoginActivity;
import com.mxx.bu_yang.adapter.SourceOrderAdapter;
import com.mxx.bu_yang.adapter.ScanStreamAdapter;
import com.mxx.bu_yang.common.CommonTitleActivity;
import com.mxx.bu_yang.dialog.QuantityDiscrepancyDialog;
import com.mxx.bu_yang.dialog.ScanSuccessDialog;
import com.mxx.bu_yang.dialog.UpLoadSuccessDialog;
import com.mxx.bu_yang.response.MaterialCodeResponse;
import com.mxx.bu_yang.response.ScanCodeHouseOutResponse;
import com.mxx.bu_yang.response.SourceOderResponse;
import com.mxx.bu_yang.response.SourceOrderUploadRequest;
import com.mxx.common.config.ConstantsConfig;
import com.mxx.common.config.NetUrlConfig;
import com.mxx.common.observer.CommonObserver;
import com.mxx.common.observer.DefaultModelObserver;
import com.mxx.common.response.BaseEntityResponse;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：刘江飞
 * 时间：2020/10/14  16:25
 * 邮箱：642371742Z@qq.com
 * 描述：
 **/
public class WarehouseOutActivity extends CommonTitleActivity {
    private EditText et_warehouse;
    private TextView tv_check_manual;
    private ImageView iv_confirm;
    private TextView tv_customer;
    private TextView tv_department;
    private ImageView iv_scan;
    private TextView tv_cancel;
    private TextView tv_confirm;
    private SourceOrderAdapter mSourceOrderAdapter;
    private ScanStreamAdapter mScanStreamAdapter;
    private final Map<String, String> paramsMap = new HashMap<>();
    private String temporary = "";
    private TextWatcher textWatcher;

    @Override
    protected int getTitleType() {
        return TITLE_LEFT_BACK_MIDDLE_TITLE_RIGHT_NONE;
    }

    /**
     * 获取当前页面的布局文件
     *
     * @return int
     */
    @Override
    public int getLayoutResId() {
        return R.layout.activity_scan_code_warehouse_out;
    }

    @Override
    public void initView() {
        super.initView();
        et_warehouse = findViewById(R.id.et_warehouse);
        tv_check_manual = findViewById(R.id.tv_check_manual);
        iv_confirm = findViewById(R.id.iv_confirm);
        tv_customer = findViewById(R.id.tv_customer);
        tv_department = findViewById(R.id.tv_department);
        RecyclerView rv_goods_list = findViewById(R.id.rv_goods_list);
        RecyclerView rv_scan_stream = findViewById(R.id.rv_scan_stream);
        iv_scan = findViewById(R.id.iv_scan);
        tv_cancel = findViewById(R.id.tv_cancel);
        tv_confirm = findViewById(R.id.tv_confirm);

        LinearLayoutManager mManager;
        mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        mSourceOrderAdapter = new SourceOrderAdapter(R.layout.adapter_goods_list);
        initRecyclerView(rv_goods_list, mManager, mSourceOrderAdapter);

        mManager = new LinearLayoutManager(this);
        mManager.setOrientation(RecyclerView.VERTICAL);
        mScanStreamAdapter = new ScanStreamAdapter(R.layout.adapter_scan_stream);
        initRecyclerView(rv_scan_stream, mManager, mScanStreamAdapter);


        tv_title.setText("扫码出库");

        textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.i("TAG", s.toString());
            }

            @Override
            public void onTextChanged(final CharSequence s, int start, int before, int count) {
                Log.i("TAG", s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
                temporary = s.toString().replace(temporary, "");
                paramsMap.put("barcode", temporary);
                runOnUiThread(() -> {
                    et_warehouse.removeTextChangedListener(textWatcher);
                    et_warehouse.setText(temporary);
                    showScanSuccessDialog();
                    et_warehouse.addTextChangedListener(textWatcher);
                });
            }
        };


        int user_id = getUser_Id();
        paramsMap.put("userId", String.valueOf(user_id));
        paramsMap.put("billNo", "");
    }

    private void initRecyclerView(RecyclerView recyclerView, RecyclerView.LayoutManager mManager
            , BaseQuickAdapter mAdapter) {
        recyclerView.setLayoutManager(mManager);
        recyclerView.setAdapter(mAdapter);
    }

    private void showScanSuccessDialog() {
        ScanSuccessDialog successDialog = new ScanSuccessDialog();
        successDialog.setDialogDismissListener(dialog -> {
            //是否获取原单信息（"billNo"为空获取原单信息，不为空调用记录扫描流水接口）
            loadSourceOrderOrScanStream();
        });
        successDialog.show(getSupportFragmentManager(), "ScanSuccessDialog");
    }

    private void loadSourceOrderOrScanStream() {
        String billNo = paramsMap.get("billNo");
        if (billNo == null || billNo.isEmpty()) {
            loadSourceOrder();
        } else {
            loadScanStream();
        }
    }

    private void loadSourceOrder() {
        String barcode = paramsMap.get("barcode");
        String userId = paramsMap.get("userId");
        Map<String, String> params = new HashMap<>();
        params.put("barcode", barcode);
        params.put("userId", userId);
        String s = "?" + MapUrlParamsUtils.getUrlParamsByMap(params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationOut/selOutSourceList" + s)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new DefaultModelObserver(true, this) {
                    @Override
                    protected void handlerJsonObjectData(String objectJson) {
                        ScanCodeHouseOutResponse response = paramsObjectJson(objectJson);
                        loadSourceOrderInfo(response);
                        loadScanStreamInfo(response);
                        loadMaterialCode(barcode);
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        ToastUtils.showToast(WarehouseOutActivity.this, msg);
                    }

                    @Override
                    protected void onFailed(BaseEntityResponse response) {
                        super.onFailed(response);

                    }
                });
    }

    private void switchToLogin() {
        ToastUtils.showToast(this, "IP为空，请到登录页重新设置IP");
        SPUtils.put(this, "login_info", "");
        SPUtils.put(this, ConstantsConfig.BASE_URL, "");
        Intent mIntent = new Intent(this, LoginActivity.class);
        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(mIntent);
        finish();
    }

    private ScanCodeHouseOutResponse paramsObjectJson(String objectJson) {
        ScanCodeHouseOutResponse response = new ScanCodeHouseOutResponse();
        if (objectJson != null && !objectJson.isEmpty()) {
            response = new Gson().fromJson(objectJson, new TypeToken<ScanCodeHouseOutResponse>() {
            }.getType());
        }
        return response;
    }

    private void loadSourceOrderInfo(ScanCodeHouseOutResponse response) {
        if (response == null) {
            return;
        }

        String barcode = paramsMap.get("barcode");
        et_warehouse.setText(barcode);

        List<SourceOderResponse> list = response.list;
        if (list != null && !list.isEmpty()) {
            mSourceOrderAdapter.setList(list);
        }


        String custName = response.custName;
        if (custName != null && !custName.isEmpty()) {
            tv_customer.setText(custName);
        }
        String saleDeptName = response.saleDeptName;
        if (saleDeptName != null && !saleDeptName.isEmpty()) {
            tv_department.setText(saleDeptName);
        }
        String billNo = response.billNo;
        paramsMap.put("billNo", billNo);
    }

    private void loadScanStreamInfo(ScanCodeHouseOutResponse response) {
        if (response == null) {
            return;
        }
        SourceOderResponse sourceOderVO = response.sourceOderVO;
        if (sourceOderVO == null) {
            return;
        }
        List<SourceOderResponse> list = new ArrayList<>();
        list.add(sourceOderVO);
        mScanStreamAdapter.setList(list);
    }

    private void loadMaterialCode(String barcode) {
        if (barcode == null || barcode.isEmpty()) {
            ToastUtils.showToast(this, "条形码信息不能为空");
            return;
        }
        Map<String, String> request_params = new HashMap<>();
        request_params.put("barcode", barcode);
        String json = "?" + MapUrlParamsUtils.getUrlParamsByMap(request_params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationMateriel/getMaterielNumber" + json)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new DefaultModelObserver(true, this) {
                    @Override
                    protected void handlerJsonObjectData(String objectJson) {
                        refreshCurrentMaterial(objectJson);
                    }
                });
    }


    private void refreshCurrentMaterial(String objectJson) {
        String materialNo = getMaterialNum(objectJson);
        if (materialNo != null && !materialNo.isEmpty()) {
            List<SourceOderResponse> list = mSourceOrderAdapter.getData();
            if (!list.isEmpty()) {
                for (SourceOderResponse response : list) {
                    if (response != null && response.materialNumber != null
                            && response.materialNumber.equals(materialNo)) {
                        Integer actualQuantity = response.actualQuantity;
                        if (actualQuantity == null) {
                            actualQuantity = 0;
                        }
                        response.actualQuantity = actualQuantity + 1;
                        int position = list.indexOf(response);
                        mSourceOrderAdapter.notifyItemChanged(position);
                    }
                }
            }
        }
    }


    private String getMaterialNum(String objectJson) {
        String materialNo = "";
        MaterialCodeResponse response = paramsObjectJsonToObject(objectJson);
        if (response != null) {
            materialNo = response.materialNo;
        }
        return materialNo;
    }

    private MaterialCodeResponse paramsObjectJsonToObject(String objectJson) {
        MaterialCodeResponse response = new MaterialCodeResponse();
        if (objectJson != null && !objectJson.isEmpty()) {
            response = new Gson().fromJson(objectJson, new TypeToken<MaterialCodeResponse>() {
            }.getType());
        }
        return response;
    }

    private void loadScanStream() {
        String barcode = paramsMap.get("barcode");
        String billNo = paramsMap.get("billNo");
        String userId = paramsMap.get("userId");
        Map<String, String> request_params = new HashMap<>();
        request_params.put("barcode", barcode);
        request_params.put("billNo", billNo);
        request_params.put("userId", userId);
        String json = "?" + MapUrlParamsUtils.getUrlParamsByMap(request_params);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationOut/inertOutScanningFlow" + json)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new CommonObserver(true, this) {
                    @Override
                    protected void handlerJsonData(String objectJson) {
                        List<SourceOderResponse> list = paramsObjectJsonToScanResult(objectJson);
                        setScanStreamList(list);
                        loadMaterialCode(barcode);
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        ToastUtils.showToast(WarehouseOutActivity.this, msg);
                    }
                });
    }

    private List<SourceOderResponse> paramsObjectJsonToScanResult(String objectJson) {
        List<SourceOderResponse> list = new ArrayList<>();
        if (objectJson != null && !objectJson.isEmpty()) {
            list = new Gson().fromJson(objectJson, new TypeToken<List<SourceOderResponse>>() {
            }.getType());
        }

        return list;
    }

    private void setScanStreamList(List<SourceOderResponse> list) {
        if (list == null || list.isEmpty()) {
            return;
        }
        mScanStreamAdapter.setList(list);
    }

    @Override
    public void initListener() {
        super.initListener();
        tv_check_manual.setOnClickListener(this);
        iv_confirm.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
        tv_cancel.setOnClickListener(this);
        tv_confirm.setOnClickListener(this);
        et_warehouse.setOnClickListener(this);
        et_warehouse.addTextChangedListener(textWatcher);
        et_warehouse.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                temporary = et_warehouse.getText().toString();
                paramsMap.put("barcode", et_warehouse.getText().toString());
                loadSourceOrderOrScanStream();
                et_warehouse.addTextChangedListener(textWatcher);
            }
            return false;
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view.getId() == R.id.iv_confirm) {
            temporary = et_warehouse.getText().toString();
            paramsMap.put("barcode", et_warehouse.getText().toString());
            loadSourceOrderOrScanStream();
        }
        if (view.getId() == R.id.et_warehouse) {
            et_warehouse.removeTextChangedListener(textWatcher);
        }

        if (view.getId() == R.id.tv_cancel) {
            finish();
        }
        if (view.getId() == R.id.tv_confirm) {
            upload();
        }
    }

    private void upload() {
        SourceOrderUploadRequest request = getUploadRequest();
        String request_json = getJsonRequest(request);
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationOut/insertOutScanResults")
                .addParams(request_json)
                .build()
                .observable(RequestEnum.METHOD_POST_JSON_STRING)
                .subscribe(new CommonObserver(true, this) {
                    @Override
                    protected void handlerJsonData(String arrayJson) {
                        showUploadSuccessDialog();
                    }

                    @Override
                    protected void onFailed(int code, String msg) {
                        super.onFailed(code, msg);
                        if (code == 2) {
                            showQuantityDiscrepancyDialog(msg);
                        } else {
                            ToastUtils.showToast(WarehouseOutActivity.this, msg);
                        }
                    }
                });
    }

    private SourceOrderUploadRequest getUploadRequest() {
        SourceOrderUploadRequest request = new SourceOrderUploadRequest();
        String billNo = paramsMap.get("billNo");
        if (billNo != null) {
            request.fbillNo = billNo;
        }
        String userId = paramsMap.get("userId");
        if (userId != null && !userId.isEmpty()) {
            request.operatorId = Integer.parseInt(userId);
        }
        request.sourceOrderList = mSourceOrderAdapter.getData();
        return request;
    }

    private String getJsonRequest(SourceOrderUploadRequest request) {
        String json = "";
        if (request != null) {
            json = new Gson().toJson(request);
        }
        return json;
    }


    private void showQuantityDiscrepancyDialog(String tip) {
        QuantityDiscrepancyDialog discrepancyDialog = new QuantityDiscrepancyDialog();
        if (tip != null && !tip.isEmpty()) {
            tip.replace("！！！是否确认上传", "");
        }
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("hint", tip);
        discrepancyDialog.setArguments(mBundle);
        discrepancyDialog.setDialogResultListener(result -> {
            SourceOrderUploadRequest request = getUploadRequest();
            String request_json = getJsonRequest(request);
            forceStorage(request_json);
        });
        discrepancyDialog.show(getSupportFragmentManager(), "UploadCheckedDialog");
    }

    private void forceStorage(String request_json) {
        if (request_json == null || request_json.isEmpty()) {
            ToastUtils.showToast(this, "参数不足");
            return;
        }
        String baseUrl = (String) SPUtils.get(this, ConstantsConfig.BASE_URL, "");
        if (baseUrl == null || baseUrl.isEmpty()) {
            runOnUiThread(this::switchToLogin);
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl(baseUrl)
                .appendUrl("user/operationOut/forceOutScanResults")
                .addParams(request_json)
                .build()
                .observable(RequestEnum.METHOD_POST_JSON_STRING)
                .subscribe(new CommonObserver(true, this) {
                    @Override
                    protected void handlerJsonData(String objectJson) {
                        showUploadSuccessDialog();
                    }
                });
    }

    private void showUploadSuccessDialog() {
        UpLoadSuccessDialog successDialog = new UpLoadSuccessDialog();
        successDialog.setDialogDismissListener(dialog -> {
            if (dialog == null) {
                return;
            }
            dialog.dismiss();
        });
        successDialog.show(getSupportFragmentManager(), "UpLoadSuccessDialog");
    }
}
